//
//  DWMessageRequest.m
//  LGMessageAccept
//
//  Created by dangwc on 2019/9/5.
//  Copyright © 2019 dangwc. All rights reserved.
//

#import "DWMessageRequest.h"
#import "DWMessageCountModel.h"
#import "DWMessageInfoModel.h"
#import "MJExtension.h"
#import "XMLDictionary.h"

@implementation DWMessageRequest

+(void)requestUrl:(NSString *)url
       parameters:(NSDictionary *)parameters
          timeout:(NSTimeInterval)timeout
          success:(void(^)(id _Nullable responseObjeC))success
          failure:(void(^)(NSError *_Nullable error))failure{
    
    NSString *requestUrlString = url;
    NSURL *requestUrl = [NSURL URLWithString:requestUrlString];
    // POST请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestUrl];
    request.HTTPMethod = @"POST";
    // 设置请求头
    request.timeoutInterval = timeout;
    // 检验给定的对象是否能够被序列化
    if (![NSJSONSerialization isValidJSONObject:parameters]) {
        NSLog(@"格式不正确，不能被序列化");
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey:@"格式不正确，不能被序列化"};
            failure([NSError errorWithDomain:NSLocalizedDescriptionKey code:-9001 userInfo:userInfo]);
        });
        return;
    }
    //设置请求体
    
    NSString *query = DWQueryStringFromParameters(parameters);
    NSString *json = [parameters mj_JSONString];
    NSLog(@"请求地址：%@\n请求参数：%@",url,json);
    [request setHTTPBody:[query dataUsingEncoding:NSUTF8StringEncoding]];
    // 异步连接
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                failure(error);
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *responseDic = [NSDictionary dictionaryWithXMLData:data];
                success(responseDic);
            });
        }
    }];
    [dataTask resume];
}

//获取消息数量
+(void)lg_MessageCountBaseUrl:(NSString *)baseUrl userID:(NSString *)userID Callback:(void (^)(BOOL))callback{
    NSString *url1= @"PsnInfo/Remind/Interface/Service_PsnInfo_Remind.asmx/WS_PsnInfo_G_GetRemindUnReadCountByType";
    NSString *url2 = [NSString stringWithFormat:@"%@%@",baseUrl,url1];
    NSAssert(userID != nil, @"用户ID不能为空");
    NSAssert(baseUrl != nil, @"子系统地址不能为空");
    [self requestUrl:url2 parameters:@{@"UserID":userID} timeout:3 success:^(id  _Nullable responseObjeC) {
        DWMessageTypeModel *model = [DWMessageTypeModel mj_objectWithKeyValues:responseObjeC];
        __block NSInteger i = 0;
        [model.anyType enumerateObjectsUsingBlock:^(DWMessageCountModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            i=i+obj.MsgCount;
        }];
        if (i>0) {
            callback(YES);
        }else{
            callback(NO);
        }
    } failure:^(NSError * _Nullable error) {
        callback(NO);
    }];
}

//获取消息
+(void)lg_MessageInfoListBaseUrl:(NSString *)baseUrl
                      parameters:(NSDictionary *)parameters
                 CompletedHandle:(DWCompletedHandle)completedHandle{
    
    
    NSString *url1= @"PsnInfo/Remind/Interface/Service_PsnInfo_Remind.asmx/WS_PsnInfo_G_GetRemindList";
    NSString *url2 = [NSString stringWithFormat:@"%@%@",baseUrl,url1];
    
    [self requestUrl:url2 parameters:parameters timeout:5 success:^(id  _Nullable responseObjeC) {
        NSDictionary *dic = responseObjeC;
        DWMessageInfoTypeModel *model = [DWMessageInfoTypeModel mj_objectWithKeyValues:dic];
        if ([dic[@"anyType"] isKindOfClass:[NSDictionary class]]) {
            model = [DWMessageInfoTypeModel new];
            NSDictionary *singleDic = dic[@"anyType"];
            DWMessageInfoModel *infoModel = [DWMessageInfoModel mj_objectWithKeyValues:singleDic];
            if (infoModel) {
                model.anyType = @[infoModel];
            }
        }
        completedHandle(model.anyType,nil);
    } failure:^(NSError * _Nullable error) {
        completedHandle(nil,error);
    }];
    
    
}


//删除某一条消息
+(void)lg_RemoveMessageWithBaseUrl:(NSString *)baseUrl
                        parameters:(NSDictionary *)parameters
                   completedHandle:(DWCompletedHandle)completedHandle{
    
    NSString *url1= @"PsnInfo/Remind/Interface/Service_PsnInfo_Remind.asmx/WS_PsnInfo_G_DeleteRemindNews";
    NSString *url2 = [NSString stringWithFormat:@"%@%@",baseUrl,url1];
    [self requestUrl:url2 parameters:parameters timeout:5 success:^(id  _Nullable responseObjeC) {
        NSString *code = responseObjeC[@"__text"];
        completedHandle(code,nil);
    } failure:^(NSError * _Nullable error) {
        completedHandle(nil,error);
    }];
    
    
}


//删除全部消息
+(void)lg_RemoveAllMessageWithBaseUrl:(NSString *)baseUrl
                           parameters:(NSDictionary *)parameters
                      CompletedHandle:(DWCompletedHandle)completedHandle{
    NSString *url1= @"PsnInfo/Remind/Interface/Service_PsnInfo_Remind.asmx/WS_PsnInfo_G_EmptyRemindNews";
    NSString *url2 = [NSString stringWithFormat:@"%@%@",baseUrl,url1];
    [self requestUrl:url2 parameters:parameters timeout:5 success:^(id  _Nullable responseObjeC) {
        NSString *code = responseObjeC[@"__text"];
        completedHandle(code,nil);
    } failure:^(NSError * _Nullable error) {
        completedHandle(nil,error);
    }];
}


NSString * DWQueryStringFromParameters(NSDictionary *parameters) {
    NSMutableArray *mutablePairs = [NSMutableArray array];
    [parameters enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,obj];
        [mutablePairs addObject:str];
    }];
    return [mutablePairs componentsJoinedByString:@"&"];
}



@end


